package main.java.com.silence.controller.advice;

import com.silence.constant.AttributeConstant;
import com.silence.constant.ViewNameConstant;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author: Silence
 * Date: 2017/6/7 14:49
 */
@ControllerAdvice
public class CommonControllerAdvice {

    /** 数据绑定 */
    @InitBinder
    public void initBinder(HttpServletRequest request,
                           ServletRequestDataBinder binder){
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    /** 全局异常处理 */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception e){
        ModelAndView modelAndView = new ModelAndView(ViewNameConstant.SHOW_MSG);
        modelAndView.addObject(AttributeConstant.MSG, e.toString());
        return modelAndView;
    }
}
